//
//  HMRefreshControl.swift
//  02-自定义下拉刷新控件
//
//  Created by HM on 2017/7/5.
//  Copyright © 2017年 itheima. All rights reserved.
//

import UIKit
// 设置控件的高度
private let HMRefreshControlH: CGFloat = 50

// 定义下拉刷新控件的状态
enum HMRefreshControlType: String{
    case normal = "正常"
    case pulling = "下拉中"
    case refreshing = "刷新中"
}

class HMRefreshControl: UIControl {
    
    var scrollView: UIScrollView?
    
    // 记录控件状态
    var hmType:HMRefreshControlType = .normal{
        didSet{
            // 赋值(通过枚举名得到枚举值 使用rawValue)
            messageLabel.text = hmType.rawValue
            // 分别判断
            switch hmType {
            case .normal:
                print("正常")
                // 因为上个状态为下拉中 没有进入刷新中导致多减去50
                // 有几种请求进入正常(下拉中 刷新中)
                // 记录上一个值oldValue
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.scrollView?.contentInset.top -= HMRefreshControlH
                    }, completion: { (_) in
                        // 结束动画
                        self.indicatorView.stopAnimating()
                        // 显示箭头
                        self.pullrefreshImageView.isHidden = false
                    })
                }
                // 恢复箭头方向
                UIView.animate(withDuration: 0.25, animations: {
                    self.pullrefreshImageView.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    
                })
                
            case .pulling:
                print("下拉中")
                // 设置箭头的方向
                UIView.animate(withDuration: 0.25, animations: { 
                    self.pullrefreshImageView.transform = CGAffineTransform(rotationAngle: CGFloat(-3*Double.pi))
                }, completion: { (_) in
                    
                })
            case .refreshing:
                print("刷新中")
                // 隐藏箭头
                // 开启菊花动画
                UIView.animate(withDuration: 0.25, animations: { 
                    self.scrollView?.contentInset.top += HMRefreshControlH
                    self.pullrefreshImageView.isHidden = true
                    self.indicatorView.startAnimating()
                }, completion: { (_) in
                    // 发送事件告知外界刷新
                    self.sendActions(for: UIControlEvents.valueChanged)
                })
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -HMRefreshControlH, width: UIScreen.main.bounds.width, height: HMRefreshControlH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 结束刷新方法
    func endRefreshing(){
        // 设置状态为正常
        hmType = .normal
    }
    
    // 监听该控件将要添加谁身上
    override func willMove(toSuperview newSuperview: UIView?) {
        // 判断newSuperview是否为nil 而且是否是一个滚动视图
        guard let s = newSuperview as? UIScrollView else {
            return
        }
        // 记录
        scrollView = s
        // 注册观察者
        s.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
    }
    
    // 监听scrollView的contentOffset.y的变化
    /*
        - 临界点 -114(导航条64 控件高度50)
        - 正常 y >= -114(拖动中) && 状态为下拉中
        - 下拉中 y < -114(拖动中) && 状态为正常
        - 刷新中 只有松手后 且下拉中才可以是这个状态
     */
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        // 判断scrollView 是否为nil
        guard let s = self.scrollView else {
            return
        }
        
        // 计算出临界值
        let maxY = -(HMRefreshControlH + s.contentInset.top)
        // 计算出contentOffset.y
        let contentOffsetY = s.contentOffset.y
        // 判断用户是否在拖拽
        if s.isDragging {
            // 判断
            // 正常
            if contentOffsetY >= maxY && hmType == .pulling {
                hmType = .normal
            }else if contentOffsetY < maxY && hmType == .normal{
                // 下拉中
                hmType = .pulling
            }
        }else{
            // 用户松手了
            // 判断是否为下拉中
            if hmType == .pulling {
                hmType = .refreshing
            }
        }
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        backgroundColor = UIColor.gray
        // 添加控件
        addSubview(messageLabel)
        addSubview(pullrefreshImageView)
        addSubview(indicatorView)
        // 使用autoLayout
        // 代码层面使用autoLayout 把translatesAutoresizingMaskIntoConstraints false才可以使用代码进行Contraints来布局
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        // 添加约束
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        
        pullrefreshImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: pullrefreshImageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullrefreshImageView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
    }
    
    //MARK: - 懒加载控件
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textColor = UIColor.white
        lab.textAlignment = .center
        lab.text = "正常"
        return lab
    }()
    // 箭头
    private lazy var pullrefreshImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 小菊花
    private lazy var indicatorView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
        return view
    }()
    
    // 移除kvo
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
